package org.com.app.knock;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.com.app.service.SkyServiceCallback;
import org.json.JSONObject;

import z.lib.base.BaseServiceCallBack;
import z.lib.base.BaseUtils;
import z.lib.base.BaseUtils.API;
import z.lib.base.CommonAndroid;
import z.lib.base.LogUtils;
import z.lib.base.callback.RestClient;
import z.lib.base.callback.RestClient.RequestMethod;
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;

import com.app.knock.db.Account;
import com.app.knock.db.AvataList;
import com.app.knock.db.IconList;
import com.app.knock.db.Setting;
import com.knock.app.R;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseInstallation;
import com.parse.SaveCallback;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
public class KnockApplication extends Application {
	public static String objectId = "";
	public static String userName = "";
	public static ArrayList<String> listFriend = new ArrayList<String>();
	
	public static String device_send_username = "";
	public static String device_send_userid = "";
	public static String device_send_avatar = "";
	
	public static String token_device_gcm = "";
	
	public static GoogleAnalyticsTracker tracker;
	@Override
	public void onCreate() {
		super.onCreate();
		
		/*String Parse_app_key = this.getResources().getString(R.string.parse_app_key);
		String Parse_client_key = this.getResources().getString(R.string.parse_client_key);
		Parse.initialize(this, Parse_app_key, Parse_client_key);
		ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
			@Override
			public void done(ParseException e) {
				if (e == null) {
					objectId =  ParseInstallation.getCurrentInstallation().getObjectId();//ParseInstallation.getCurrentInstallation().getString("objectId");
					Log.e("regis_parse", "done:::" +objectId);
				} else {
					e.printStackTrace();
					Log.e("regis_parse", "err:" + e.getMessage());
				}
			}
		});*/
		
		tracker = GoogleAnalyticsTracker.getInstance();

	    // Start the tracker in manual dispatch mode...
	    tracker.startNewSession("UA-61198382-1", this);

	    // ...alternatively, the tracker can be started with a dispatch interval (in seconds).
	    //tracker.startNewSession("UA-YOUR-ACCOUNT-HERE", 20, this);
	}

	@SuppressLint("NewApi")
	public void execute(final RequestMethod method, final String api, final Map<String, String> params, final BaseServiceCallBack cheerzServiceCallBack) {
		if (cheerzServiceCallBack != null) {
			cheerzServiceCallBack.onStart();
		}
//		params.put("req[lang]", new Setting(this).getLangStr());
		if (!params.containsKey("_user_id")) {
			params.put("_user_id", new Account(this).getUserId());
		}

		if (!params.containsKey("_token")) {
			LogUtils.e("token", "abc==" + new Account(this).getToken());
			params.put("_token", new Account(this).getToken());//a
		}
		new AsyncTask<String, String, String>() {
			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				if (cheerzServiceCallBack != null) {
					if (client.getResponseCode() == 200) {
						try {
							JSONObject jsonObject = new JSONObject(client.getResponse());
							LogUtils.e("AAAAAAAAAAAA", jsonObject.toString());
							String is_succes = CommonAndroid.getString(jsonObject, BaseUtils.KEY.is_success);
							String err_msg = CommonAndroid.getString(jsonObject, BaseUtils.KEY.err_msg);
							LogUtils.e("AAAAAAAAAAAA", "is_succes==="+is_succes);
							if (BaseUtils.VALUE.STATUS_API_SUCCESS.equals(is_succes)) {
								cheerzServiceCallBack.onSucces(client.getResponse());
							} else {
								cheerzServiceCallBack.onError(err_msg);
							}

							return;
						} catch (Exception exception) {
						}
					}

//					cheerzServiceCallBack.onError(getString(new Setting(KnockApplication.this).isLangEng() ? R.string.msg_err_connect : R.string.msg_err_connect_j));
					cheerzServiceCallBack.onError(getString(R.string.msg_err_connect));
				}
			}

			private RestClient client;

			@Override
			protected String doInBackground(String... paramStrs) {

				client = new RestClient(BaseUtils.API.BASESERVER + api);
//				client.addHeader("Content-Type", "application/json; charset=utf-8");
//				client.addHeader("Accept", "application/json; charset=utf-8");
				Set<String> keys = params.keySet();

				for (String key : keys) {
					client.addParam(key, params.get(key));
				}

				client.execute(method);

				updateData(api, params, client);

				return null;
			}
		}.execute("");
	}

	private void updateData(String api, Map<String, String> params, RestClient client) {
		if (API.API_USER_LOGIN.equals(api) || API.API_USER_REGISTER.equals(api)) {
			new Account(this).updateWhenLogin(client.getResponseCode(), this, client.getResponse(), params);
		}else if(API.API_DATA.equals(api)){
			new AvataList(this).updateAvataList(client.getResponse());
			new IconList(this).updateIconList(client.getResponse());
		}
		
		/*else if (API.API_SERVICE_LIST.equals(api)) {
			if ("service-list".equals(params.get("req[param][slug]"))) {
				// home update
				new ServiceList(this).updateServiceList(client.getResponse());
			}
		}*/
	}

	private SkyServiceCallback skyService;

	public void initService(final SkyServiceCallback back) {
		// if (skyService != null) {
		// back.onInitSuccess();
		// return;
		// }
		// Intent intent = new Intent(skyService.ACTION);
		// bindService(intent, new ServiceConnection() {
		//
		// @Override
		// public void onServiceDisconnected(ComponentName name) {
		// skyService = null;
		// back.onInitFail();
		// }
		//
		// @Override
		// public void onServiceConnected(ComponentName name, IBinder service) {
		// skyService = ((CheerzBin) service).getCheerzService();
		// back.onInitSuccess();
		// }
		// }, BIND_AUTO_CREATE);
	}

	/**
	 * FONTS
	 * 
	 * @author teemo
	 * 
	 */
	public interface IConfigApplication {
		public void onXStart();

		public void onSuccess();
	}

	@SuppressLint("NewApi")
	public void init(final IConfigApplication configApplication) {
		configApplication.onXStart();

		new AsyncTask<String, String, String>() {
			@Override
			protected String doInBackground(String... params) {

				for (String font : fonts) {
					if (!hashMap.containsKey(font)) {
						try {
							hashMap.put(font, Typeface.createFromAsset(getAssets(), "fonts/" + font));
						} catch (Exception exception) {

						}
					}
				}

				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				configApplication.onSuccess();
			}
		}.execute("");
	}

	public HashMap<String, Typeface> hashMap = new HashMap<String, Typeface>();
	public static final String fonts[] = new String[] {//
	"helveticaneuebold.ttf",//
			"KozGoPr6N-ExtraLight.otf",//

			"helveticaneuelight.ttf",//
			"helveticaneuemedium.ttf",//

	};

	public void setFonts(int txtType, TextView editText) {
		try {
			if (txtType <= fonts.length - 1) {
				editText.setTypeface(hashMap.get(fonts[txtType]));
			}
		} catch (Exception exception) {

		}
	}
	
	public static void savedatafriend(Context activity) {
		SharedPreferences pref = activity.getApplicationContext().getSharedPreferences("FavoriteList2", 0);
		Editor editor = pref.edit();
		StringBuilder csvList = new StringBuilder();
		for (int i = 0; i < listFriend.size(); i++) {
			csvList.append(listFriend.get(i));
			csvList.append(",");
		}
		editor.putString("FList2", csvList.toString());
		editor.commit();
	}

	public static void getdatafriend(Context activity) {
		try {
			SharedPreferences pref = activity.getApplicationContext().getSharedPreferences("FavoriteList2", 0);
			String csvList = pref.getString("FList2", null);
			String[] items = csvList.split(",");
			listFriend = new ArrayList<String>();
			listFriend.clear();
			for (int i = 0; i < items.length; i++) {
				String temp = items[i].toString();
				if(!listFriend.contains(temp) && !temp.equalsIgnoreCase("")){
					listFriend.add(items[i].toString());
				}
				
			}
			Collections.sort(listFriend);
		} catch (Exception exception) {

		}
	}
	
}